package odgs.message.server;

import java.util.HashMap;
import java.util.List;

import odgs.Connection;
import odgs.Explorer;
import odgs.ExplorerNode;
import odgs.LoginedGridNode;
import odgs.GridState;
import odgs.Result;
import odgs.message.Message;
import odgs.message.MessageHandler;
import odgs.message.MessageProcessor;

public class LoginRequestHandler implements MessageHandler
{
	public void execute(MessageProcessor processor, Message msg, Connection con)
	{
		String id = (String) msg.get("id");
		
		Message reMsg = new Message(Message.LOGIN_RESPONSE);

		int result = processor.getServerManager().login(id,con.getIP());
		if(result == Result.OK)
		{
			GridState state = processor.getServerManager().getGridState();
			List<ExplorerNode> explorer = processor.getServerManager().getExplorerData();
			reMsg.put("state", state);
			reMsg.put("explorer", explorer);
			reMsg.setResult(Result.LOGIN_OK);
			con.sendMessage(reMsg);
			
			Message updateMsg = new Message(Message.UPDATE_GRID_STATE);
			updateMsg.put("state", state);
			processor.getNetworkManager().broadcastMessage(updateMsg);
		}
		else
		{
			reMsg.setResult(result);
			con.sendMessage(reMsg);
		}
	}
}